/** Part of Zombie Navigator
	Copyright © 2016  Zombie Navigator Developers
	
	@file
	@module
	@license AGPL-3.0+
	
*/ 'use strict';


/* Used modules */
const _sdkFsPath = require('sdk/fs/path');
const _sdkIoFile = require('sdk/io/file');

const _jsmDownloads = require('./_jsm').import('resource://gre/modules/Downloads.jsm');


/* Private properties */

/**
	@private
	@returns {Promise}
*/
const getTargetPath = suggestedName => {
	const Downloads = _jsmDownloads.Downloads;
	const sdkFsPath = _sdkFsPath;
	const sdkIoFile = _sdkIoFile;
	
	return new Promise((resolve, reject) => {
		Downloads.getPreferredDownloadsDirectory()
		.then(dir => {
			const {basename, join} = sdkFsPath;
			const {exists} = sdkIoFile;
			
			const name = basename(suggestedName);
			const path = join(dir, name);
			if (!exists(path)) {
				resolve('' + path);
			}
			
			const maxRetries = 100;
			for (let i = 0; i < maxRetries; i++) {
				const path = join(dir, name + '-' + i);
				if (!exists(path)) {
					resolve('' + path);
				}
			}
			reject('No filename available');
		});
	});
};


/* Internal APIs */

/** @protected */
const initiateDownload = (uri, suggestedName, isPrivate, referrer) => {
	const Downloads = _jsmDownloads.Downloads;
	
	return new Promise((resolve, reject) => {
		getTargetPath(suggestedName).then(path => {
			Downloads.createDownload({
				source: '' + uri
				,isPrivate: !!isPrivate
				,referrer: referrer ? referrer + '' : null
				,target: '' + path
			})
			.then(download => {
				Downloads.getList(Downloads.ALL)
				.then(list => {
					list.add(download); // Not cleaned automatically
					download.start()
					.then(() => resolve('' + path))
					.catch(e => {
						reject('' + e);
					});
				});
			});
		});
	});
};


/* Exports */
exports.initiateDownload = initiateDownload;

// vim: ts=4 noet ai

